package com.cql.framework.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.cql.common.constant.HttpStatus;
import com.cql.common.core.base.AjaxResult;
import com.cql.common.utils.MessageUtils;
import com.cql.common.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理类 返回未授权
 * <p>
 * 用来解决认证过的用户访问无权限资源时的异常
 *
 * @author cql
 */
@Component
public class PreAccessDeniedHandler implements AccessDeniedHandler {

    final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        logger.error("请求访问: " + request.getRequestURI() + " 接口， 没有访问权限");
        int code = HttpStatus.UNAUTHORITY.getCode();
        String msg = MessageUtils.message("exception.unauthority");
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}

